﻿#include "stdafx.h"
#include "LoginDlg.h"
#include "ui_LoginDlg.h"
#include "UserInfoDlg.h"
#include "AppFunctions.h"
#include "FrameHelper.h"
#include <QCryptographicHash>
#include <QKeyEvent>

UserInfo LoginDlg::userInfo;

LoginDlg::LoginDlg(QWidget *parent)
	: QDialog(parent)
{
	ui = new Ui::LoginDlg();
	ui->setupUi(this);

	bLogin = false;
	pDlgUser = new UserInfoDlg;

	pFrameHelper = new FrameHelper(this);
	pFrameHelper->addDragWidget(this);
	pFrameHelper->setCloseButton(ui->btnClose);
	pFrameHelper->setMinimizedButton(ui->btnMin);

	//set Login Window Icon
	setWindowIcon(QIcon("image:/sys/appIcon.png"));

	pOrgTree = new OrganizationTree;
	pDlgUser->setRecordModel(pOrgTree);

	ui->tipInfo->setVisible(false);
	ui->editName->installEventFilter(this);

	if (gMapConfigs.contains("LOGIN/USER"))
	{
		ui->editName->setText(gMapConfigs.value("LOGIN/USER").toString());
	}

	if (gMapConfigs.contains("LOGIN/PWD"))
	{
		ui->editPwd->setText(gMapConfigs.value("LOGIN/PWD").toString());
		ui->checkPwd->setChecked(true);
	}

}

LoginDlg::~LoginDlg()
{
	delete pDlgUser;
	delete pFrameHelper;
	delete ui;
}

bool LoginDlg::login(const QString & SQL, const QVariant & Root)
{
	if (pOrgTree)
	{
		QString Error;
		strSQL = SQL;
		varRoot = Root;
		if (!initModel(Error))
		{
			Hint(ui->tipInfo, HT_ERROR, Error);
		}
	}

	if (exec() == QDialog::Accepted)
	{
		this->close();
	}
	return bLogin;
}

UserInfo LoginDlg::getUserInfo()
{
	return userInfo;
}

void LoginDlg::on_btnLogin_clicked()
{
    const QString & name = ui->editName->text();
    const QString & pwd = ui->editPwd->text();
	QString error;

	bLogin = check(name, pwd, error);

	if (bLogin == false)
	{
		Hint(ui->tipInfo, HT_ERROR, error);
		return;
	}

	if (ui->checkPwd->isChecked())
	{
		gMapConfigs["LOGIN/USER"] = name;
		gMapConfigs["LOGIN/PWD"] = pwd;
		saveConfig(*getConfig());
	}
	else
	{
		gMapConfigs.remove("LOGIN/USER");
		gMapConfigs.remove("LOGIN/PWD");
		saveConfig(*getConfig());
	}

	accept();
}

bool LoginDlg::initModel(QString & Error)
{
	bool bInit = pOrgTree->select(strSQL, Error);
	if (bInit)
	{
		pOrgTree->setCol("NAME", CF_SHOW);
		pOrgTree->setFieldCol("ID", "PID");
		pOrgTree->setRoot(varRoot);
		//pDlgUser->expandTree(0);
	}

	return bInit;
}

bool LoginDlg::check(const QString & name, const QString & pwd, QString & error)
{
	error.clear();

	if (pOrgTree->rowCount() == 0)
	{
		if(!initModel(error))
			return false;
	}

	if (userInfo.strUserCode.isEmpty())
	{
		QRecordTree & record = pOrgTree->records();
		int row = record.getFetchString("CODE", name);

		if (row != -1)
		{
			userInfo.strUserCode = name;
			userInfo.strUserName = record.data(row, "NAME").toString();
			userInfo.strUserID = record.data(row, "ID").toString();
			userInfo.strUserPasswd = record.data(row, "PASSWD").toString();
			userInfo.strDeptID = record.data(row, "PID").toString();

			int deptRow = record.getFetchRow("ID", userInfo.strDeptID);
			if (deptRow != -1)
			{
				userInfo.strDeptName = record.data(deptRow, "NAME").toString();
			}

		}
	}

	if (name.compare(userInfo.strUserCode, Qt::CaseInsensitive) == 0)
	{
		QString strMd5;
		QByteArray bb;
		bb = QCryptographicHash::hash(pwd.toLocal8Bit(), QCryptographicHash::Md5);
		strMd5.append(bb.toHex());
		if (strMd5.compare(userInfo.strUserPasswd, Qt::CaseInsensitive) == 0)
			return true;
	}

	error = tr("Name or password is not right");
	return false;
}

bool LoginDlg::eventFilter(QObject * obj, QEvent * e)
{
	if (obj == ui->editName && e->type() == QEvent::MouseButtonDblClick)
	{
		if (pDlgUser->exec() == QDialog::Accepted)
		{
			userInfo = pDlgUser->getCurrentUserInfo();
			pDlgUser->close();
			ui->editName->setText(userInfo.strUserCode);
		}
		return true;
	}
	return false;
}

void LoginDlg::keyPressEvent(QKeyEvent *e)
{
	if (e->key() == Qt::Key_Return)
	{
		on_btnLogin_clicked();
	}
	//QDialog::keyPressEvent(e);
}

/***********************************************************************************************************************************/
OrganizationTree::OrganizationTree(QObject * parent) :QRecordTreeModel(parent)
{
}

OrganizationTree::~OrganizationTree()
{
}

QVariant OrganizationTree::data(const QModelIndex & index, int role) const
{
	if (!index.isValid()) return QVariant();

	int RowIndex = index.internalId();
	short Col = dsRecords.showRecords().at(index.column());

	if (role == Qt::DisplayRole) 
		return dsRecords.data(RowIndex, Col);

	if (role == TREE_ROLE_ID) 
		return dsRecords.data(RowIndex, ID);

	if (role == TREE_ROLE_PID || role == TREE_ROLE_DEPTID) 
		return dsRecords.data(RowIndex, PID);

	if (role == TREE_ROLE_USERCODE)
		return dsRecords.data(RowIndex, "CODE");

	if (role == TREE_ROLE_USERNAME)
		return dsRecords.data(RowIndex, "NAME");

	if (role == TREE_ROLE_PASSWD)
		return dsRecords.data(RowIndex, "PASSWD");

	if (role == TREE_ROLE_DEPTNAME)
	{
        const QVariant & deptID = dsRecords.data(RowIndex, PID);
		int deptRow = dsRecords.getFetchRow(ID, deptID);

		return dsRecords.data(deptRow, "NAME");
	}

	return QVariant();
}

Qt::ItemFlags OrganizationTree::flags(const QModelIndex &index) const
{
	if (rowCount(index) > 0)
        return Qt::ItemFlags(~Qt::ItemIsSelectable & QAbstractItemModel::flags(index));

	return QRecordTreeModel::flags(index);
}
